package com.qifan.energy.widget.dialog;

import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.qifan.energy.adapter.ProductDetailSpecAdapter;
import com.qifan.energy.bean.vo.CartItemVO;
import com.qifan.energy.mvp.callback.IEventBuyCallback;
import com.qifan.energy.mvp.callback.IOnClickListener;
import com.qifan.energy.R;
import com.qifan.energy.bean.result.GoodsDetailResult;
import com.qifan.energy.global.GlideApp;
import com.qifan.energy.util.CheckUtil;
import com.qifan.energy.util.DensityUtil;
import com.qifan.energy.util.ToastUtils;
import com.qifan.energy.util.ViewUtils;

import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class AddCartBottomDialog extends DialogFragment {

    private ImageView iconIv;
    private TextView priceTv;
    private TextView nameTv;
    private RecyclerView recyclerView;
    private ProductDetailSpecAdapter adapter;
    private int buyCount = 1;//默认一件
    private double price = 0;//价格 默认0
    private GoodsDetailResult detailResult = null;//外部传参
    private List dataList = new LinkedList<GoodsDetailResult.ProductAttributeListBean>();

    private IEventBuyCallback callback = new IEventBuyCallback() {

        @Override
        public void onCancel() {

        }

        @Override
        public void onComfirm(CartItemVO cartItemVO) {

        }
    };

    /* 对外提供 */
    public void setEventCallback(IEventBuyCallback callback) {
        this.callback = callback;
    }

    /* 显示 */
    public AddCartBottomDialog showNow2(@Nullable FragmentManager manager, @Nullable String tag) {
        showNow(manager, tag);
        return this;
    }

    /* 设置icon */
    public AddCartBottomDialog setModel(@NonNull GoodsDetailResult result){
        detailResult = result;
        if (!TextUtils.isEmpty(result.getProduct().getPic())){
            GlideApp.with(this)
                    .load(result.getProduct().getPic())
                    .placeholder(R.mipmap.icon_default_square)
                    .error(R.mipmap.icon_default_square)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .into(iconIv);
        }
        if (!TextUtils.isEmpty(result.getProduct().getName())){
            nameTv.setText(result.getProduct().getName());
        }
        priceTv.setText(String.valueOf(result.getProduct().getPrice()));
        price = result.getProduct().getPrice();
        if (CheckUtil.hasContent(detailResult.getSkuStockList())) {
            GoodsDetailResult.SkuStockListBean skuBean = detailResult.getSkuStockList().get(0);
            priceTv.setText(String.valueOf(skuBean.getPrice()));
        }

        /* 设置分组标题|Content */
        if (CheckUtil.hasContent(detailResult.getProductAttributeList())) {
            dataList.addAll(detailResult.getProductAttributeList());
            if (dataList.size() > 4) {//对recyclerView限高
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                int contentH = DensityUtil.getScreenHeight() - ViewUtils.getStatusBarHeight(getActivity());
                layoutParams.height = DensityUtil.dip2px(DensityUtil.px2dip(getActivity(),contentH) - 300);
                recyclerView.setLayoutParams(layoutParams);
            }
        }
        /* 设置详情规格 */
        adapter.setDetailResult(result);
        adapter.setIOnClickListener(new IOnClickListener() {
            @Override
            public void onClick() {

                //计算价格
                GoodsDetailResult.SkuStockListBean currentSkuBean = getCurrentSkuBean();
                if (null != currentSkuBean) {
                    priceTv.setText(String.valueOf(currentSkuBean.getPrice()));
                }
            }
        });
        adapter.notifyDataSetChanged();
        return this;
    }

    /* 获取当前选中的sku */
    private GoodsDetailResult.SkuStockListBean getCurrentSkuBean(){
        List<Map<String,String>> mapArray = new LinkedList<>();
        Map<Integer, Integer> specMap = adapter.getSpecMap();
        for (int i = 0; i < specMap.size(); i++) {
            String key = detailResult.getProductAttributeList().get(i).getName();
            String[] split = detailResult.getProductAttributeValueList().get(i).getValue().split(",");
            List<String> specList = Arrays.asList(split);
            Integer index = specMap.get(i);
            String value = specList.get(index);
            Map<String,String> spMap = new LinkedHashMap<>();
            spMap.put("key",key);
            spMap.put("value",value);
            mapArray.add(spMap);
        }
        String spJsonString = JSON.toJSONString(mapArray);
        if (CheckUtil.hasContent(detailResult.getSkuStockList())) {
            for (GoodsDetailResult.SkuStockListBean skuBean : detailResult.getSkuStockList()) {
                if (TextUtils.equals(skuBean.getSpData(),spJsonString)) {
                    return skuBean;
                }
            }
        }
        return null;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        //去掉dialog的标题，需要在setContentView()之前
        this.getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        Window window = this.getDialog().getWindow();
        //去掉dialog默认的padding
        window.getDecorView().setPadding(0, 0, 0, 0);
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        //设置dialog的位置在底部
        lp.gravity = Gravity.BOTTOM;
        //设置dialog的动画
        lp.windowAnimations = R.style.BottomDialogAnimation;
        window.setAttributes(lp);
        window.setBackgroundDrawable(new ColorDrawable());

        final View view = inflater.inflate(R.layout.fragment_dialog_bottom_addcart, null);
        findView(view);
        return view;
    }

    /* 设置View */
    private void findView(View view) {
        recyclerView = view.findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        adapter = new ProductDetailSpecAdapter(getActivity(),dataList);
        recyclerView.setAdapter(adapter);

        TextView confirmTv = view.findViewById(R.id.confirm_tv);
        priceTv = view.findViewById(R.id.price_tv);
        nameTv = view.findViewById(R.id.name_tv);
        ImageView closeIv = view.findViewById(R.id.close_iv);
        iconIv = view.findViewById(R.id.icon_iv);
        closeIv.setOnClickListener(v -> {
            dismiss();
            if (callback != null) callback.onCancel();
        });
        confirmTv.setOnClickListener(v -> {
            dismiss();
            CartItemVO cartItemVO = new CartItemVO();
            cartItemVO.setProductId(detailResult.getProduct().getId());
            cartItemVO.setPrice(detailResult.getProduct().getPrice());
            if (CheckUtil.hasContent(detailResult.getSkuStockList())) {
                GoodsDetailResult.SkuStockListBean currentSkuBean = getCurrentSkuBean();
                if (null != currentSkuBean) {
                    cartItemVO.setPrice(currentSkuBean.getPrice());
                    cartItemVO.setProductAttr(currentSkuBean.getSpData());
                }
            }
            cartItemVO.setQuantity(buyCount);
            cartItemVO.setProductPic(detailResult.getProduct().getPic());
            cartItemVO.setProductName(detailResult.getProduct().getName());
            cartItemVO.setProductSubTitle(detailResult.getProduct().getSubTitle());
            cartItemVO.setDistributeStatus(detailResult.getProduct().getDistributeStatus());
            if (CheckUtil.hasContent(detailResult.getSkuStockList())) {
                GoodsDetailResult.SkuStockListBean currentSkuBean = getCurrentSkuBean();
                if (currentSkuBean != null){
                    cartItemVO.setProductSkuId(currentSkuBean.getId());
                    cartItemVO.setProductSkuCode(currentSkuBean.getSkuCode());
                }
            }
            cartItemVO.setDistributeAmount(detailResult.getProduct().getDistributeAmount());
            cartItemVO.setGiftGamePoint(detailResult.getProduct().getGiftGamePoint());
            cartItemVO.setGiftCouponAmount(detailResult.getProduct().getGiftCouponAmount());
            cartItemVO.setGiftTimeCard(detailResult.getProduct().getGiftTimeCard());
            if (callback != null) callback.onComfirm(cartItemVO);
        });

        ImageView decIv = view.findViewById(R.id.dec_iv);
        ImageView addIv = view.findViewById(R.id.add_iv);
        TextView countTv = view.findViewById(R.id.count_tv);
        addIv.setOnClickListener(v -> {
            if (detailResult.getProduct().getStock() <= buyCount){
                ToastUtils.showShort("商品库存不足了耶~");
                return;
            }
            int quantity = Integer.parseInt(countTv.getText().toString());
            buyCount = ++quantity;
            countTv.setText(String.valueOf(quantity));
        });
        decIv.setOnClickListener(v -> {
            int quantity = Integer.parseInt(countTv.getText().toString());
            if (quantity>1){
                buyCount = --quantity;
                countTv.setText(String.valueOf(quantity));
            }
        });
    }
}
